import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 游戏主程序入口
 * @author cxh
 * @date 2022/4/26 16:22
 */
public class Main {

    /**
     * 程序入口
     * @param args
     */
    public static void main(String[] args) throws Exception{
        startGame(5,5);
    }

    /**
     * 开始游戏
     * @param roomNumber 同时进行游戏的线程数
     * @param gameNumber 每个线程进行多少次比赛
     */
    private static void startGame(Integer roomNumber,Integer gameNumber) throws Exception{

        if (roomNumber == null || roomNumber <= 0){
            return;
        }

        //创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                roomNumber,
                roomNumber,
                1,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(roomNumber),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );

        for (int i = 0; i < roomNumber; i++) {
            threadPoolExecutor.execute(new GameRunnable(gameNumber));
        }

        //休眠1秒等结果
        Thread.sleep(2000);

        List<GameResult> gameResultList = GameCollect.getInstance().getGameResultList();
        gameResultList.stream().forEach(gameResult -> {
            String finger1 = gameResult.getPlayer1().getFinger();
            String finger2 = gameResult.getPlayer2().getFinger();

            gameResult.getPlayer1().setFinger(FingerEnum.getFinger(finger1));
            gameResult.getPlayer2().setFinger(FingerEnum.getFinger(finger2));
        });
        Map<String, List<GameResult>> result = gameResultList.stream().collect(Collectors.groupingBy(GameResult::getRoomName));
        System.out.println("result = " + JSONUtil.toJsonStr(result));


    }

}
